#include "queue_source.h"

#include <boost/bind.hpp>

#include "audio_source_factory.h"
#include "interfaces/queue_cursor_interface.h"
#include "interfaces/queue_interface.h"
#include "source_descriptor.h"

using namespace pita;

QueueSource::QueueSource(QueueCursorInterface& cursor) :
	cursor_ (&cursor),
	current_index_ (cursor.position())
{
	cursor_->changeSignal.connect(
		boost::bind(&QueueSource::positionChanged, this));
}

bool QueueSource::finished() const
{
	return false;
}

bool QueueSource::nextChunk(DataChunk& chunk,
							   unsigned int timeout)
{
	if (current_ && current_->finished())
		cursor_->next();

	updateCurrent();

	if (!current_) return false;

	return current_->nextChunk(chunk, timeout);
}

void QueueSource::positionChanged()
{
	current_.reset();
}

void QueueSource::updateCurrent() const
{
	if (!current_)
	{
		try
		{
			SourceDescriptor desc =
				cursor_->queue().sourceDescriptor(
					cursor_->position());
			
			current_index_ = cursor_->position();
			current_ = AudioSourceFactory::create(desc);
		}
		catch (const IndexError&)
		{
			// This is ok...it means that the cursor is at the end
			// of the playlist.
		}

	}
}
